package com.htwy.core.controller;

import com.htwy.core.model.Account;
import com.htwy.ext.BaseController;
import com.htwy.kits.RandomKit;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;

public class AccountController extends BaseController<Account> {

    @Override
    protected Account dao() {
        return Account.dao;
    }

    @Override
    public boolean beforeSave(Account entity) {
        if(StrKit.isBlank(entity.getUuid())) {
            Account account = dao().findByUsername(entity.getAccount());
            if (account == null) {
                String salt = RandomKit.getNextSalt(32);
                entity.setSalt(salt);
                String encrypted = HashKit.md5(entity.getAccount() + salt + (StrKit.isBlank(entity.getPassword())? entity.getAccount():entity.getPassword()));
                entity.setPassword(encrypted);
                return true;
            } else {
                renderJson(Ret.fail().set("msg","该用户已经存在"));
                return false;
            }
        }
        return true;
    }

    public void resetPwd(){
        String uuid = getPara("uuid");
        String password = getPara("password");
        if(StrKit.isBlank(uuid)){
            renderJson(Ret.fail().set("msg","该用户不存在"));
            return;
        }
        if(StrKit.isBlank(password)){
            renderJson(Ret.fail().set("msg","密码不能为空"));
            return;
        }

        Account account = dao().findById(uuid);
        if(account == null){
            renderJson(Ret.fail().set("msg","该用户不存在"));
            return;
        }

        String salt = RandomKit.getNextSalt(32);
        account.setSalt(salt);
        String encrypted = HashKit.md5(account.getAccount() + salt + password);
        account.setPassword(encrypted);
        account.update();
        renderJson(Ret.ok());
    }

    public void saveRoles(){
        String userId = getPara("userId");
        String[] roleIds = getParaValues("roleIds");

        if(StrKit.isBlank(userId)){
            renderJson(Ret.fail().set("msg","用户不能为空"));
        }else{
            dao().deleteRolesByAccountId(userId);
            if(roleIds != null && roleIds.length > 0){
                for (String roleId : roleIds){
                    dao().addAccountRole(userId, roleId);
                }
            }
            renderJson(Ret.ok());
        }

    }

    public void getRoleIdsByUserId(){
        String userId = getPara("userId");
        if(StrKit.isBlank(userId)){
            renderJson(Ret.fail().set("msg","用户不能为空"));
        }else{
            renderJson(Ret.ok().set("data", dao().getRoleIdsByAccountId(userId)));
        }
    }

    public void getByRoleIdNoCache(){
        String roleId = getPara("roleId");
        renderJson(Ret.ok().set("data",dao().getByRoleIdNoCache(Kv.by("roleId",roleId))));
    }
}